﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Windows.Controls;

namespace BadHabit.Factory.Controls {

    /// <summary>
    /// Interaction logic for TaskViewer.xaml
    /// </summary>
    public partial class TaskDataGrid : TaskViewerBase {


        protected BindingListCollectionView FilteredView { get; set; }


        /// <summary>
        /// Default constructor.
        /// </summary>
        public TaskDataGrid() {
            InitializeComponent();                        
        }

        private void CreateFilteredView(Data.TaskDataSet.TaskDataTable tasks) {
                         
             FilteredView = (BindingListCollectionView) CollectionViewSource.GetDefaultView(tasks);
            
        }



        private void TaskViewerBase_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) {
            if (!(DataContext is Data.TaskDataSet.TaskDataTable))
                return;
            CreateFilteredView((Data.TaskDataSet.TaskDataTable)DataContext);
            taskDataGrid.ItemsSource = FilteredView; 
            ApplyFilter();
        }

        /// <summary>
        /// Applies the filter on th listbox.
        /// </summary>        
        protected override void ApplyFilter() {

            if (FilteredView != null)
                FilteredView.CustomFilter = FilterString;

        }

        

        /// <summary>
        /// When inserting a new task row, fillits default values.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void taskDataGrid_InitializingNewItem(object sender, Microsoft.Windows.Controls.InitializingNewItemEventArgs e) {
            Data.TaskDataSet.TaskRow task = Helper.GetRowFromRowView<Data.TaskDataSet.TaskRow>(e.NewItem);                
            SetDefaultTaskValues(task);
        }

        /// <summary>
        /// Every time that BacklogItemFilter change to something diferent of Null
        /// this property is setted to true.
        /// So override this to only allow new rows at the datagrid in those cases.
        /// </summary>
        protected override bool AllowAddTask {
            set {
                taskDataGrid.CanUserAddRows = value;                             
            }
        }

        public override void PasteTasks(string[] tasks) {

            if (!CanAddTask())
                return;

            Data.TaskDataSet.TaskDataTable taskTable = DataContext as Data.TaskDataSet.TaskDataTable;

            foreach (String taskName in tasks) {
                Data.TaskDataSet.TaskRow newTask = taskTable.NewTaskRow();
                SetDefaultTaskValues(newTask);
                newTask.TaskType = (short)TaskTypes.PROJECT_TASK;
                newTask.TaskName = taskName;
                taskTable.AddTaskRow(newTask);
            }

            taskDataGrid.UpdateLayout();
            ApplyFilter();
            
        }

        private void ViewTaskTailCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) {
            if(taskDataGrid.SelectedItems.Count==0)
                return;
            TaskPanelBase.OpenTaskTailWindow(Helper.GetRowFromRowView<Data.TaskDataSet.TaskRow>(taskDataGrid.SelectedItems[0]));
        }

        


        private void CancelTaskCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) {

            foreach (object item in taskDataGrid.SelectedItems) {
                Data.TaskDataSet.TaskRow task = Helper.GetRowFromRowView<Data.TaskDataSet.TaskRow>(item);
                task.Status = (short)TaskStatus.TASK_CANCELED;
            }
            
                
        }

        private void DoneTaskCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) {
            foreach (object item in taskDataGrid.SelectedItems) {
                Data.TaskDataSet.TaskRow task = Helper.GetRowFromRowView<Data.TaskDataSet.TaskRow>(item);
                task.Status = (short) TaskStatus.TASK_DONE;
            }
            
        }

        private void UnitChangeTaskCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) {

            Microsoft.Windows.Controls.DataGridCell cell = e.OriginalSource as Microsoft.Windows.Controls.DataGridCell;
            if (cell == null)
                return;

            string newUnit = e.Parameter as string;
            if(newUnit==null)
                return;

            foreach (object item in taskDataGrid.SelectedItems) {
                Data.TaskDataSet.TaskRow otherTask = Helper.GetRowFromRowView<Data.TaskDataSet.TaskRow>(item);
                otherTask.UnitName = newUnit;
            }

            
        }

        private void IsPayableChangeTaskCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) {
            Microsoft.Windows.Controls.DataGridCell cell = e.OriginalSource as Microsoft.Windows.Controls.DataGridCell;
            if (cell == null)
                return;

            Data.TaskDataSet.TaskRow task = Helper.GetRowFromRowView<Data.TaskDataSet.TaskRow>(cell.DataContext);
            if (task == null)
                return;

            foreach (object item in taskDataGrid.SelectedItems) {
                Data.TaskDataSet.TaskRow otherTask = Helper.GetRowFromRowView<Data.TaskDataSet.TaskRow>(item);
                otherTask.Payable = task.Payable;
            }
        }


        private void AddTaskMaterial_Executed(object sender, ExecutedRoutedEventArgs e) {
            Data.TaskDataSet.TaskRow task = Helper.GetRowFromRowView<Data.TaskDataSet.TaskRow>(taskDataGrid.SelectedItem);
            if (task == null)
                return;
            if (!VerifyAddTaskMaterial(task))
                return;
            AddTaskMaterial(task.TaskUId, Client.FactoryMainWindow.CurrentProject.ProjectDocBase, false);            
        }

        private void AddTaskMaterialLink_Executed(object sender, ExecutedRoutedEventArgs e) {
            Data.TaskDataSet.TaskRow task = Helper.GetRowFromRowView<Data.TaskDataSet.TaskRow>(taskDataGrid.SelectedItem);
            if (task == null)
                return;
            if (!VerifyAddTaskMaterial(task))
                return;
            AddTaskMaterial(task.TaskUId, Client.FactoryMainWindow.CurrentProject.ProjectDocBase, true);
        }

        private void MoveTaskCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) {
            Data.TaskDataSet.TaskRow task = Helper.GetRowFromRowView<Data.TaskDataSet.TaskRow>(((System.Windows.Controls.Control)e.OriginalSource).DataContext);
            if (task == null)
                return;
            System.Data.DataRowView backlogItem = e.Parameter as System.Data.DataRowView;
            if (backlogItem == null)
                return;

            if (taskDataGrid.SelectedItems.Count > 1) {
                MessageBoxResult d = Windows.Error.ShowDialog(
                    String.Format(Properties.Resources.Move_tasks_to_item, taskDataGrid.SelectedItems.Count, backlogItem["BacklogItemNumber"])
                    , Properties.Resources.Move_Task, MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No);
                if (d == MessageBoxResult.No)
                    return;

                foreach (object item in taskDataGrid.SelectedItems) {
                    Data.TaskDataSet.TaskRow otherTask = Helper.GetRowFromRowView<Data.TaskDataSet.TaskRow>(item);
                    TaskPanelBase.MoveTask(otherTask, backlogItem["SprintUId"].ToString(), backlogItem["BacklogItemUId"].ToString(), (short)backlogItem["BacklogItemNumber"], false);
                }

            }
            else
                TaskPanelBase.MoveTask(task, backlogItem["SprintUId"].ToString(), backlogItem["BacklogItemUId"].ToString(), (short)backlogItem["BacklogItemNumber"], true);
        }

        
        #region UGLY WAY TO SOLVE THE TAB NAVIGATION FOCUS 

        private void CurrentCellChanged(object sender, EventArgs e) {
            
            //DataGrid dg = sender as DataGrid;
            //if (!(dg.CurrentColumn is DataGridTemplateColumn))
            //    return;

            //dg.BeginEdit();
            
            
        }

        private void taskDataGrid_PreparingCellForEdit(object sender, DataGridPreparingCellForEditEventArgs e) {

            //BadHabit.WPFTools.ComboBox control = (BadHabit.WPFTools.ComboBox)Helper.GetObjectOfTypeInVisualTree<BadHabit.WPFTools.ComboBox>(e.EditingElement);
            //if (control == null)
            //    return;
            //if (control.IsEnabled && control.IsTabStop)
            //    control.Focus();
        }

        #endregion


        private void OpenItemDetail_Executed(object sender, ExecutedRoutedEventArgs e) {



            Windows.TaskDetail w = new BadHabit.Factory.Windows.TaskDetail(Client.FactoryMainWindow.CurrentProject, TaskView);
            w.Show();
        }


        public BindingListCollectionView TaskView {
            get {
                return (BindingListCollectionView)CollectionViewSource.GetDefaultView(taskDataGrid.ItemsSource);
            }
        }
      
       

                   
    }
}
